package com.poorstu.web;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.common.base.web.BaseAction;
import com.poorstu.manager.FileManager;
import com.poorstu.model.FilesMod;

public class FileLoadAction extends BaseAction {
	
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
	try {
		int fileId=Integer.parseInt(request.getParameter("fid"));
		 FileManager fileManager=(FileManager)getBean("fileManager");
		FilesMod files= fileManager.selectFileById(fileId);
		String  fileRoad=files.getFileRoad();
		
		
		 File file = new File(fileRoad);    
         String filename = file.getName();    
             
         //取得文件的扩展名ext    
         String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();    
             
         InputStream fis = new BufferedInputStream(new FileInputStream(fileRoad));    
         byte[] buffer = new byte[fis.available()];    
         fis.read(buffer);    
         fis.close();    
             
         response.reset();    
         response.addHeader("Content-Disposition", "attachment;filename="+new String(filename.getBytes()));    
         response.addHeader("Content-Length", ""+file.length()); //设置返回的文件类型    
         OutputStream toClient = new BufferedOutputStream(response.getOutputStream()); //得到向客户端输出二进制数据的对象    
         //根据扩展名声称客户端浏览器mime类型    
         if(ext.equals("DOC"))    
             response.setContentType("application/msword");    
         else   
             response.setContentType("application/octet-stream"); //设置返回的文件类型    
         toClient.write(buffer); //输出数据    
         toClient.flush();    
         toClient.close();    
		
	} catch (Exception e) {
		e.printStackTrace();
		return mapping.findForward("failure");
	}
  return null;
	}
}
